package find.prj.prog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ConsoleURLTester {

	private static boolean isXMLLoaded = false;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HttpURLConnection httpCon = null;
		Document xmldoc = null;
		try {
			URL url = new URL("http://atwar.blogs.nytimes.com/feed/");
			httpCon = (HttpURLConnection)url.openConnection();
			httpCon.setRequestMethod("GET");
			httpCon.setRequestProperty("Content-Type", "application/rss+xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			xmldoc = dBuilder.parse(new InputSource(new BufferedReader(new InputStreamReader(httpCon.getInputStream()))));
			isXMLLoaded = true;
		}
		catch (MalformedURLException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			System.out.println("Not a XML file");
			e.printStackTrace();
		}
		finally {
			if(httpCon != null)
				httpCon.disconnect(); 
	    }
		
		if (isXMLLoaded) {
			if (xmldoc.getDocumentElement().getNodeName().toLowerCase() != "rss") {
				System.out.println("That XML does not have RSS document element");
				return;
			}
			NodeList items = xmldoc.getElementsByTagName("item");
			for (int i=0; i< items.getLength(); i++) {
				Node item = items.item(i);
				if (item.getNodeType() == Node.ELEMENT_NODE) {
					System.out.println(((Element) item).getElementsByTagName("title").item(0).getTextContent());
					System.out.println(((Element) item).getElementsByTagName("link").item(0).getTextContent());
					System.out.println(((Element) item).getElementsByTagName("description").item(0).getTextContent()+"\n\n----------\n");
				}
			}
		}
	}
}
